package com.webridge.plm.util;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import org.apache.log4j.Logger;

import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.folder.Folder;
import wt.part.WTPart;
import wt.pom.Transaction;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.util.WTAttributeNameIfc;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.config.LatestConfigSpec;
import wt.vc.wip.CheckoutLink;
import wt.vc.wip.WorkInProgressHelper;

public class FileUtil {
    private static Logger log = Logger.getLogger(FileUtil.class.getName());

    public static void updateSecondaryContent(Object secondaryContent, WTDocument doc) {
        try {
            ApplicationData applicationdata = ApplicationData.newApplicationData(doc);
            applicationdata.setRole(ContentRoleType.SECONDARY);
            InputStream ins = (InputStream) secondaryContent;
            applicationdata = ContentServerHelper.service.updateContent(doc, applicationdata, ins);
        } catch (WTPropertyVetoException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (WTException e) {
            e.printStackTrace();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static WTObject addAttachment(WTObject object, String strAttachmentFilePath, String attachementName)
    {
        File asrc = new File(strAttachmentFilePath,"UTF-8");
        if (asrc != null && asrc.exists()) {
            InputStream attSymbleInputStream = null;
            try {
                attSymbleInputStream = new FileInputStream(asrc);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                log.debug("geti fileInputStream failed!");
                e1.printStackTrace();
            }
            if (object != null && attSymbleInputStream != null) {
                log.debug("path:" + strAttachmentFilePath+",name:" + attachementName);
                object = (WTObject) createSECONDARY((ContentHolder) object, attachementName, attSymbleInputStream);
            }
        }

        try {
            object = (WTObject) PersistenceHelper.manager.save(object);
            object = (WTObject) PersistenceServerHelper.manager.restore(object);
        } catch (WTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return object;
    }

    public static ContentHolder createSECONDARY(ContentHolder object,
            String attachmentName, InputStream isAttachment) {
        log.debug("inputStream:" + isAttachment);
        if (object != null && attachmentName != null && isAttachment != null
                && attachmentName.length() > 0) {

            try {
                Transaction transaction = new Transaction();
                try {

                    ApplicationData appdata = ApplicationData
                            .newApplicationData(object);
                    appdata.setRole(ContentRoleType.SECONDARY);
                    transaction.start();
                    // delete first
                    ContentHolder content = ContentHelper.service
                            .getContents(object);
                    Vector vApplicationData = ContentHelper.getApplicationData(content);
                    for (int i = 0; i < vApplicationData.size(); i++) {
                        ApplicationData applicationdata = (ApplicationData) vApplicationData
                                .elementAt(i);
                        if (applicationdata.getFileName().equals(attachmentName)) {
                            log.debug("...清除附件："
                                    + applicationdata.getFileName());
                            ContentServerHelper.service.deleteContent(content,
                                    applicationdata);
                            break;
                        }
                    }

                    appdata.setFileName(attachmentName);
                    appdata.setUploadedFromPath(attachmentName);
                    appdata.setDescription("系统自动生成");
                    appdata = ContentServerHelper.service.updateContent(object,
                            appdata, isAttachment);
                    appdata = (ApplicationData) PersistenceHelper.manager.save(appdata);

                    transaction.commit();
                    transaction = null;
                } catch (WTException wte) {
                    log.debug("error1: " + wte.getMessage());
                } catch (WTPropertyVetoException wtpve) {
                    log.debug("error2: " + wtpve.getMessage());
                } catch (PropertyVetoException pve) {
                    log.debug("error3: " + pve.getMessage());
                } catch (IOException ioe) {
                    log.debug("error4: " + ioe.getMessage());
                } finally {
                    if (transaction != null) {
                        transaction.rollback();
                    }
                }
                isAttachment.close();
            } catch (IOException ioe) {
                // System.out.println(ioe.getMessage());
            }
            return object;
        } else {
            return null;
        }
    }

    public static WTDocument getLatestWTDocument(String docNumber) throws WTException
    {
        if (docNumber == null || docNumber.length() == 0)
            return null;

        QuerySpec qs = new QuerySpec(WTDocument.class);
        SearchCondition scNumber = new SearchCondition(WTDocument.class,
                WTDocument.NUMBER, SearchCondition.EQUAL, docNumber
                        .toUpperCase());
        SearchCondition scLatestIteration = new SearchCondition(
                WTDocument.class, WTAttributeNameIfc.LATEST_ITERATION,
                SearchCondition.IS_TRUE);
        qs.appendWhere(scNumber);
        qs.appendAnd();
        qs.appendWhere(scLatestIteration);

        QueryResult qr = PersistenceHelper.manager.find(qs);
        if (qr != null && qr.hasMoreElements())
            qr = (new LatestConfigSpec()).process(qr);

        if (qr != null && qr.hasMoreElements())
            return (WTDocument) qr.nextElement();

        return null;
    }

    public static WTDocument getWorkingCopyOfDoc(WTDocument doc) throws WTException,
            WTPropertyVetoException {
        WTDocument workingDoc = null;
        if (!WorkInProgressHelper.isCheckedOut(doc)) {
            Folder folder = WorkInProgressHelper.service.getCheckoutFolder();
            CheckoutLink checkoutlink = WorkInProgressHelper.service.checkout(
                    doc, folder, SessionHelper.manager.getPrincipal()
                            .getName());
            workingDoc = (WTDocument) checkoutlink.getWorkingCopy();
        } else {
            if (!WorkInProgressHelper.isWorkingCopy(doc)) {
                workingDoc = (WTDocument) WorkInProgressHelper.service
                        .workingCopyOf(doc);
            } else {
                workingDoc = doc;
            }
        }
        return workingDoc;
    }

    public static void main(String[] args) {
        try {
            WTDocument doc = FileUtil.getLatestWTDocument("0000000001");

            String strAttachmentFilePath = "/tmp/当幸福来敲门BD国英双语双字[电影天堂www.dy2018.com].mkv";
            String attachementName = "当幸福来敲门BD国英双语双字[电影天堂www.dy2018.com].mkv";
            FileUtil.addAttachment(doc, strAttachmentFilePath, attachementName);
            WorkInProgressHelper.service.checkin(doc, "update attachment");
        } catch (WTException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WTPropertyVetoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
